package server

import (
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/go-kratos/swagger-api/openapiv2"
	"github.com/gorilla/handlers"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/sdk/trace"
	v1 "shop-demo/api/shop/bff/v1"
	"shop-demo/app/shop/bff/internal/conf"
	"shop-demo/app/shop/bff/internal/service"
)

func NewHTTPServer(c *conf.Server, tp *trace.TracerProvider, logger log.Logger, service *service.ShopService) *http.Server {
	opts := []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			tracing.Server(),
			logging.Server(logger),
		),
		http.Filter(handlers.CORS(
			handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
			handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}),
			handlers.AllowedOrigins([]string{"*"}),
		)),
	}
	otel.SetTracerProvider(tp)

	if c.Grpc.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}

	if c.Grpc.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}

	if c.Grpc.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}

	server := http.NewServer(opts...)
	handler := openapiv2.NewHandler()
	server.HandlePrefix("/openapi/", handler)
	v1.RegisterShopHTTPServer(server, service)
	return server
}
